/*
 * File Name :  LoginApp.js
 */

import Mn from 'backbone.marionette';
import LoginView from '../views/LoginView.js';
import Radio from 'backbone.radio';
import AppRouter from 'marionette.approuter';
import { ajax_call } from '../../tools.js';
import { tanhDependencies } from 'mathjs';

const Controller = Mn.Object.extend({
    initialize(options){
        this.channel = Radio.channel('login');
        this.view = options['rootView'];
    },
    login(){
        this.view.showLogin();
    }
});
const Router = AppRouter.extend({
    appRoutes: {'login': 'login'}
});

const LoginComponent = Mn.View.extend({
    regions: {popin: '.popin-container'},
    tagName: "div",
    template: _.template("<div class='popin-container'></div>"),
    showLogin(){
        this.showChildView('popin', new LoginView({}));
    }
});

const LoginAppClass = Mn.Application.extend({
    channelName: 'auth',
    region: '#login_form',
    onStart(){
        console.log("Starting the login application");
        const view = new LoginComponent({});
        const controller = new Controller({rootView: view});
        this.router = new Router({controller: controller});

        let region = this.getRegion();
        this.showView(view);
        this.checkAuth();
    },
    url: '/api/v1/login',
    radioEvents: {
        'login': 'onLogin',
    },
    initialize: function(){
        this.ok_callback = null;
        this.error_callback = null;
    },
    checkAuth(){
        // On checke l'authentification, si c'est ok on continue
        // Si ce n'est pas ok, une redirection automatique vers #login est faite dans la partie jquery (cf tools.js)
        ajax_call(
            this.url + "?action=check", 
            {},
            'GET',
            {
                success: (result) => this.onAuthSuccess(result),
            }
        )
    },
    setAuthCallbacks(callbacks){
        /*
         * Define authentication callbacks that should be fired
         * on successfull authentication
         */
        this.callbacks = callbacks;
    },
    onLogin(datas, onAuthOk, onAuthFailed){
        var callbacks = this.callbacks;
        this.ok_callback = onAuthOk;
        this.error_callback = onAuthFailed;
        ajax_call(
            this.url,
            datas,
            'POST',
            {
                success: this.onAuthSuccess.bind(this),
                error: this.onAuthError.bind(this)
            }
        );
    },
    onAuthSuccess(result){
        if (result['status'] == 'success'){
            _.each(this.callbacks, function(callback){
                if (! _.isUndefined(callback)){
                    callback();
                }
            });
            if (this.ok_callback){
                this.ok_callback(result);
            }
        } else {
            if (this.error_callback){
                this.error_callback(result);
            }
        }
    },
    onAuthError(xhr){
        if (xhr.status == 400){
               if (_.has(xhr.responseJSON, 'errors')){
                   this.error_callback(xhr.responseJSON.errors);
               } else {
                   this.error_callback();
               }
        } else {
            alert('Erreur serveur : contactez votre administrateur');
        }
    }
});
const LoginApp = new LoginAppClass();
export default LoginApp;
